<template>
  <!-- 页面头部 -->
  <div class="page-header">
    <div class="header-left">
      <h1 class="page-title">工序分类</h1>
    </div>
    <div class="header-right">
      <el-button type="primary" :icon="Plus" @click="handleAdd">新增</el-button>
      <el-button :icon="Download" @click="handleExport">导出</el-button>
    </div>
  </div>

  <!-- 搜索区域 -->
  <div class="search-section">
    <div class="search-form">
      <el-input
        v-model="searchText"
        placeholder="请输入工序分类编号或名称"
        clearable
        style="width: 300px; margin-right: 16px"
      />
      <el-button type="primary" :icon="Search" @click="handleSearch">
        搜索
      </el-button>
    </div>
  </div>

  <!-- 表格区域 -->
  <div class="table-section">
    <!-- 表格工具栏 -->
    <div class="table-toolbar">
      <el-checkbox v-model="selectAll" @change="handleSelectAll">全选</el-checkbox>
      <span class="selected-info">已选择 {{ selectedRows.length }} 项</span>
    </div>

    <!-- 数据表格 -->
    <el-table
      ref="tableRef"
      v-loading="loading"
      :data="tableData"
      stripe
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="序号" type="index" width="80" />
      <el-table-column prop="processCategoryNumber" label="工序分类编号" min-width="150" />
      <el-table-column prop="processCategoryName" label="工序分类名称" min-width="150" />
      <el-table-column label="排序" prop="sortOrder" width="60" />
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.isActive ? 'success' : 'danger'">
            {{ row.isActive ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="remarks" label="备注" min-width="200" show-overflow-tooltip />
      <el-table-column prop="processCount" label="工序数量" width="100" />
      <el-table-column prop="createTime" label="创建时间" width="220">
        <template #default="{ row }">
          {{ formatDateTime(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link size="small" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button type="danger" link size="small" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="pagination.pageIndex"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handlePageSizeChange"
        @current-change="handlePageChange"
      />
    </div>
  </div>

  <!-- 新增/编辑弹窗 -->
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="600px"
    @close="handleDialogClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      @submit.prevent
    >
      <el-form-item label="工序分类编号" prop="processCategoryNumber">
        <el-input
          v-model="formData.processCategoryNumber"
          placeholder="请输入工序分类编号"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>
      
      <el-form-item label="工序分类名称" prop="processCategoryName">
        <el-input
          v-model="formData.processCategoryName"
          placeholder="请输入工序分类名称"
          maxlength="100"
          show-word-limit
        />
      </el-form-item>
      
      <el-form-item label="排序" prop="sortOrder">
        <el-input-number
          v-model="formData.sortOrder"
          :min="0"
          :max="9999"
          placeholder="请输入排序"
          style="width: 100%"
        />
      </el-form-item>
      
      <el-form-item label="状态" prop="isActive">
        <el-switch
          v-model="formData.isActive"
          active-text="启用"
          inactive-text="禁用"
        />
      </el-form-item>
      
      <el-form-item label="备注" prop="remarks">
        <el-input
          v-model="formData.remarks"
          type="textarea"
          :rows="3"
          placeholder="请输入备注"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Download,
  Search,
  Edit,
  Delete
} from '@element-plus/icons-vue'
import { getProcessCategoryPage, exportProcessCategories, createProcessCategory, updateProcessCategory, deleteProcessCategory } from '@/services/ProcessManagementApi'
import type { ProcessCategory, ProcessCategoryPageParams, ProcessCategoryApiResponse, ProcessCategoryCreateDto, ProcessCategoryUpdateDto } from '@/types/process'

// 时间格式化函数
const formatDateTime = (dateTime: string | null | undefined): string => {
  if (!dateTime) return '-'
  
  try {
    const date = new Date(dateTime)
    if (isNaN(date.getTime())) return '-'
    
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    
    return `${year}年${month}月${day}日${hours}时${minutes}分${seconds}秒`
  } catch (error) {
    console.error('时间格式化错误:', error)
    return '-'
  }
}

// 响应式数据
const loading = ref(false)
const searchText = ref('')
const tableData = ref<ProcessCategory[]>([])
const selectedRows = ref<ProcessCategory[]>([])
const selectAll = ref(false) // 新增：控制全选
const tableRef = ref() // 表格引用

// 分页数据
const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0
})

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const submitLoading = ref(false)
const formRef = ref()

// 表单数据
const formData = ref<ProcessCategoryCreateDto & { id?: number }>({
  processCategoryNumber: '',
  processCategoryName: '',
  sortOrder: 0,
  isActive: true,
  remarks: ''
})

// 表单验证规则
const formRules = {
  processCategoryNumber: [
    { required: true, message: '请输入工序分类编号', trigger: 'blur' },
    { max: 50, message: '工序分类编号不能超过50个字符', trigger: 'blur' }
  ],
  processCategoryName: [
    { required: true, message: '请输入工序分类名称', trigger: 'blur' },
    { max: 100, message: '工序分类名称不能超过100个字符', trigger: 'blur' }
  ],
  sortOrder: [
    { required: true, message: '请输入排序', trigger: 'blur' },
    { type: 'number', min: 0, max: 9999, message: '排序必须在0-9999之间', trigger: 'blur' }
  ]
}

// 获取行索引（考虑分页）
const getRowIndex = (index: number) => {
  return (pagination.pageIndex - 1) * pagination.pageSize + index + 1
}

// 加载数据
const loadData = async () => {
  try {
    loading.value = true
    const params: ProcessCategoryPageParams = {
      NumberOrName: searchText.value.trim() || undefined,
      pageIndex: pagination.pageIndex,
      pageSize: pagination.pageSize
    }

    console.log('开始加载工序分类数据，参数:', params)
    const response = await getProcessCategoryPage(params)
    console.log('工序分类数据响应:', response)
    
    // 根据控制台日志，修复数据解析逻辑
    if (response.code === 200) {
      // 数据直接在response的pageData字段中，不在response.data中
      tableData.value = response.pageData || []
      pagination.total = response.totaCount || 0
      console.log('成功加载数据:', {
        total: pagination.total,
        dataLength: tableData.value.length,
        data: tableData.value,
        rawResponse: response
      })
      // 清空选择状态
      selectedRows.value = []
      selectAll.value = false
      
      if (tableData.value.length === 0) {
        console.warn('数据数组为空，但API调用成功')
      }
    } else {
      console.error('API返回错误:', response)
      ElMessage.error(response.msg || '获取数据失败')
      tableData.value = []
      pagination.total = 0
      selectAll.value = false // 没有数据时取消全选
    }
  } catch (error) {
    console.error('加载工序分类数据失败:', error)
    ElMessage.error('加载数据失败，请稍后重试')
    tableData.value = []
    pagination.total = 0
    selectAll.value = false // 加载失败时取消全选
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  pagination.pageIndex = 1
  loadData()
}

// 选择变化处理
const handleSelectionChange = (selection: ProcessCategory[]) => {
  selectedRows.value = selection
  // 更新全选状态
  selectAll.value = tableData.value.length > 0 && selectedRows.value.length === tableData.value.length
}

// 全选/取消全选处理
const handleSelectAll = (checked: boolean) => {
  if (checked) {
    // 全选：通过表格方法选中所有行
    tableData.value.forEach(row => {
      tableRef.value?.toggleRowSelection(row, true)
    })
  } else {
    // 取消全选：清空所有选择
    tableRef.value?.clearSelection()
  }
}

// 分页大小变化
const handlePageSizeChange = (val: number) => {
  pagination.pageSize = val
  pagination.pageIndex = 1
  loadData()
}

// 当前页变化
const handlePageChange = (val: number) => {
  pagination.pageIndex = val
  loadData()
}



// 导出Excel
const handleExport = async () => {
  try {
    ElMessage.info('正在导出数据...')
    
    // 使用当前搜索条件进行导出
    const exportParams: { NumberOrName?: string; IsActive?: boolean } = {}
    
    if (searchText.value.trim()) {
      exportParams.NumberOrName = searchText.value.trim()
    }
    
    const result = await exportProcessCategories(exportParams)
    
    if (result.success) {
      ElMessage.success('导出成功！')
    } else {
      ElMessage.error(result.message)
    }
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请重试')
  }
}

// 弹窗方法
const handleAdd = () => {
  dialogTitle.value = '新增工序分类'
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row: ProcessCategory) => {
  dialogTitle.value = '编辑工序分类'
  isEdit.value = true
  formData.value = {
    id: row.id,
    processCategoryNumber: row.processCategoryNumber,
    processCategoryName: row.processCategoryName,
    sortOrder: row.sortOrder,
    isActive: row.isActive,
    remarks: row.remarks || ''
  }
  dialogVisible.value = true
}

const handleDelete = async (row: ProcessCategory) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除工序分类"${row.processCategoryName}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const result = await deleteProcessCategory(row.id!)
    if (result.code === 200) {
      ElMessage.success('删除成功')
      await loadData()
    } else {
      ElMessage.error(result.msg || '删除失败')
    }
  } catch (error) {
    // 用户取消删除
  }
}

const handleDialogClose = () => {
  resetForm()
  dialogVisible.value = false
}

const resetForm = () => {
  formData.value = {
    processCategoryNumber: '',
    processCategoryName: '',
    sortOrder: 0,
    isActive: true,
    remarks: ''
  }
  formRef.value?.resetFields()
}

const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    submitLoading.value = true
    
    let result
    if (isEdit.value) {
      result = await updateProcessCategory(formData.value as ProcessCategoryUpdateDto)
    } else {
      result = await createProcessCategory(formData.value)
    }
    
    if (result.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
      dialogVisible.value = false
      await loadData()
    } else {
      ElMessage.error(result.msg || '操作失败')
    }
  } catch (error) {
    console.error('表单提交失败:', error)
  } finally {
    submitLoading.value = false
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.process-classification {
  padding: 20px;
  background: #fff;
  min-height: calc(100vh - 120px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e8e8e8;
}

.header-left {
  display: flex;
  align-items: center;
}

.page-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.header-right {
  display: flex;
  gap: 12px;
}

.search-section {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px;
  background: #fafafa;
  border-radius: 8px;
}

.search-form {
  display: flex;
  align-items: center;
}

.table-section {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.table-toolbar {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e8e8e8;
}

.selected-info {
  margin-left: 20px;
  font-size: 14px;
  color: #606266;
}

.pagination-section {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  padding-top: 16px;
  border-top: 1px solid #e8e8e8;
}

/* 表格样式调整 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table__header) {
  background-color: #f5f7fa;
}

:deep(.el-table th) {
  background-color: #f5f7fa !important;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table td) {
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-table tr:hover > td) {
  background-color: #f5f7fa !important;
}

/* 按钮样式 */
.el-button + .el-button {
  margin-left: 8px;
}

/* 标签样式 */
.el-tag {
  border-radius: 4px;
}
</style> 